package com.example.security.controller;

import com.example.security.annotation.RequirePermission;
import com.example.security.annotation.RequirePermissions;
import com.example.security.common.PageResult;
import com.example.security.enums.Logical;
import com.example.security.entity.SysUser;
import com.example.security.common.Result;
import com.example.security.dto.UserDTO;
import com.example.security.dto.UserQuery;
import com.example.security.service.UserService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
@Tag(name = "用户管理接口")
public class UserController {

    private final UserService userService;

    @RequirePermissions(value = {"system:user:list", "system:user:query"}, logical = Logical.OR)
    @GetMapping("/list")
    public Result<List<SysUser>> list(UserQuery query) {
        PageResult<SysUser> userPage = userService.getUserPage(query);
        return Result.ok(userPage.getList());
    }

    @RequirePermissions("system:user:add")
    @PostMapping
    public Result<Void> add(@RequestBody @Valid UserDTO user) {
         userService.createUser(user);
         return Result.ok();
    }

    @RequirePermissions({"system:user:edit", "system:user:update"})
    @PutMapping
    public Result<Void> update(@RequestBody @Valid UserDTO user) {
         userService.updateUser(user);
         return Result.ok();
    }

    @RequirePermissions("system:user:delete")
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
         userService.deleteUser(id);
         return Result.ok();
    }

    @PutMapping("/{userId}/roles")
    @RequirePermission("system:user:assign")
    @Operation(summary = "分配用户角色")
    public ResponseEntity<Void> assignRoles(
            @PathVariable Long userId,
            @RequestBody List<Long> roleIds
    ) {
        userService.assignRoles(userId, roleIds);
        return ResponseEntity.ok().build();
    }
} 